/*
 * @Author: your name
 * @Date: 2020-12-10 09:19:35
 * @LastEditTime: 2020-12-28 13:40:45
 * @LastEditors: Please set LastEditors
 * @Description: 一些工具方法
 * @FilePath: \gitee-WeBi\js\zz\tool\tool.js
 */
(function() {
    // -----------------------------------------------------------
    /* 页面tab栏和侧边栏的对象名标识 */
    window.zzTabsObjectName = "zzTabs";
    window.zzSideMenuObjectName = "zzSideMenu"; 
    // -----------------------------------------------------------

    // -----------------------------------------------------------
    /* userRoles 用户角色 ---S */
    function UserRoles(opt) {
        //
        var keyName = opt.keyName || 'name';
        var valueName = opt.valueName || 'id';
        var rolesData = opt.rolesData || [];
        this.keyName = keyName;
        this.valueName = valueName;
        this.rolesData = []; //角色数据
        this.rolesType = {}; //角色类型汇总
        this.roleQZ = "role-"; //角色key值前缀
        this.roleCount = 0; //角色数量
        this.initRoleFns = {}; //角色对应的默认方法
        if ($.isArray(rolesData) && rolesData.length) {
            $.each(rolesData, $.proxy(function(i,item){
                this.rolesData.push($.extend({}, item))
                this.rolesType[this.roleQZ + item[this.valueName]] = {
                    [this.keyName]: item[this.keyName],
                    [this.valueName]: item[this.valueName]
                }
            },this));
            this.roleCount = this.rolesData.length; //角色数量
            //与角色对应的默认方法
            $.each(this.rolesData, $.proxy(function(i,item){
                this.initRoleFns[item[this.valueName]] = function() {}
            },this));
            //console.log(this.initRoleFns);
            //this.showRolesInfo();
        } else {
            console.error("未获取到角色数据？请检查");
        }
    }
    UserRoles.prototype = {
        constructor:UserRoles,
        //去空格
        trim(str) {
            return str.replace(/^\s+|\s+$/g, "").replace(/\s+/g, "");
        },
        //显示所有角色信息
        showRolesInfo() {
            if (!this.rolesData.length) return;
            $.each(this.rolesType, function(name,item){
                console.warn(name+'角色id为'+item[this.valueName]+',角色名称为'+item[this.keyName]);
            });
        },
        getRoleId(role) { //检查role字段是否存在并提示
            if (!this.rolesData.length) return;
            var role = this.trim(role);
            if (!(/^(role\-)/g.test(role))) {
                console.error("请传（role-数字）的字段，否则无法获取角色信息！");
                //this.showRolesInfo();
                return;
            }
            return this.rolesType[role]&&this.rolesType[role][this.valueName];
        },
        getRoleInfo(role) { //根据角色获取对应信息
            if (!this.rolesData.length) return;
            var role = this.trim(role);
            if (!(/^(role\-)/g.test(role))) {
                console.error("请传（role-数字）的字段，否则无法获取角色信息！");
                //this.showRolesInfo();
                return;
            }
            return this.rolesType[role]&&this.rolesType[role];
        },
        createFnsByRoles(fn) { 
            var fn = fn || function(){return {}};
            //创建与角色相关的方法
            //展示角色信息
            //this.showRolesInfo();
            //判断角色数据中是否包含sysRole
            //console.log($vue);
            //console.log(sysRole);
            if (!this.rolesData.length) {
                return {
                    "undefined"() {
                        console.error("系统角色数据中暂无对应的角色，请联系管理人员！");
                    }
                };
            }
            //
            return $.extend( 
                {
                    "undefined"() {
                        console.error("系统角色数据中暂无对应的角色，请联系管理人员！");
                    }
                },
                this.initRoleFns,
                fn.call(this, this.rolesType));
        }
    };
    window.zzUserRolesFn = UserRoles;
    /* userRoles 用户角色 ---E */
    // -----------------------------------------------------------

    /* FormatTreeData ---S */
    function FormatTreeData(opt) {
        this.id = opt.id || "id";
        this.pId = opt.pId || "parent_id";
        this.emitId = opt.emitId || "0";
        this.treeJson = {};
    }
    FormatTreeData.prototype = {
        getTreeData:function(data) {
            //console.log(data);
            for (var i = 0, len = data.length; i < len; i++) {
                var t = data[i];
                if (!this.treeJson[t[this.pId]]) {
                    this.treeJson[t[this.pId]] = [];
                    this.treeJson[t[this.pId]].push(t);
                } else {
                    this.treeJson[t[this.pId]].push(t);
                }
            }
            //console.log(this.treeJson);
            //
            function format(pId) {
                var result = [];
                if (!this.treeJson[pId]) {
                    return result;
                }
                for (var i in this.treeJson[pId]) {
                    var t = this.treeJson[pId][i];
                    t.children = format.call(this, t[this.id]);
                    result.push(t);
                }
                return result;
            }
            return format.call(this, this.emitId);
        },
        transferTreeData:function(treeData) {
            let result = [];
            treeData.forEach(item => {
                result.push(item);
                pushDataToResult(item.children);
            });

            function pushDataToResult(arr) {
                while (arr.length) {
                    let item = arr.shift();
                    result.push(item);
                    if (item.children) {
                        pushDataToResult(item.children);
                    }
                }
            }
            result.forEach(item => {
                delete item.children;
            })
            return result;
        },
        reset:function(opt) {
            this.id = opt.id || "id";
            this.pId = opt.pId || "parent_id";
            this.emitId = opt.emitId || "0";
            this.treeJson = null;
            this.treeJson = {};
            return this;
        }
    };
    window.zzFormatTreeData = FormatTreeData;
    /* FormatTreeData ---E */
    // -----------------------------------------------------------
    
    /* 获取项目路径 ---S */
    window.zzGetRealPath = function(){
        try {
            var localObj = window.location;
            var contextPath = localObj.pathname.split("/")[1];
            var basePath = localObj.protocol + "//" + localObj.host + "/" + contextPath + "/";
            return basePath;
        } catch (error) {
            return "---zzGetRealPath---";
        }
    }
    /* 获取项目路径 ---E */
    // -----------------------------------------------------------
    
    /* 获取location.search 或者 location.hash的参数值 ---S */
    window.zzGetHrefQueryString = function(name) {
        try {
            const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            const urlObj = window.location;
            var r = urlObj.href.indexOf('#') > -1 ? urlObj.hash.split("?")[1].match(reg) : urlObj.search.substr(1).match(reg);
            console.log("---r---",r);
            if (r != null) return unescape(r[2]);
            return null;
        } catch (error) {
            console.log("---zzGetQueryString___error---",error);
            return null;
        }
    };
    /* 获取location.search 或者 location.hash的参数值 ---E */
    //-------------------------------------------------------------

    /*  */
    //-------------------------------------------------------------

    /* sessionStorage ---S */
    // --- 设置
    window.zzSSSetItem = function(key,data){ 
        try {
            sessionStorage.setItem(key,JSON.stringify(data));
        } catch (error) {
            console.warn("---sessionStorage.setItem出错啦---",error);
        }
    };
    // --- 获取
    window.zzSSGetItem = function(key){ 
        try {
            var result = sessionStorage.getItem(key);
            return result?JSON.parse(result):null;
        } catch (error) {
            console.warn("---sessionStorage.getItem出错啦---",error);
            return null;
        }
    };
    // --- 删除
    window.zzSSRemoveItem = function(key){ 
        try {
            sessionStorage.removeItem(key);
        } catch (error) {
            console.warn("---sessionStorage.removeItem---",error);
        }
    };
    /* sessionStorage ---E */
    //-------------------------------------------------------------
    
    //-------------------------------------------------------------
    /* 获取css属性的数值(宽，高,left,top...) ---S */
    window.zzGetCssPropNum = function(str){
        try {
            var regx = /(\-|px)/g;
            return str?str.replace(regx,"")*1:"";
        } catch (error) {
            console.warn("---zzGetCssPropNum出错啦---",error);
            return "";
        }
    };
    /* 获取css属性的数值(宽，高,left,top...) ---E */
    //-------------------------------------------------------------

    /* 子页面相关 ---S */
    /**
     * @description: 设置页面容器的最小高度并显示页面
     * @param {
     * * num：内容区的上下内边距
     * }
     * @return {*}
     */
    window.zzSetIframeFluidMH = function(num){
        // --- 子页面内容区高度
        $(".zz-iframe-fluid_content").css({
            "min-height":$(window).innerHeight()-num
        }).closest("#zz-main_iframe").css({
            "display":"block"
        });
        // --- 子页面document绑定点击事件
        $(document).off("click").on("click",function(){
            try {
                // --- 隐藏已展开的侧边栏菜单
                //alert(top.zzType);
                var tSideBarObj = top[zzSideMenuObjectName + top.zzType];
                //console.log("---tSideBarObj---",tSideBarObj);
                tSideBarObj.hideActiveMenuItem();
            } catch (error) {
                console.log("---子页面document绑定的点击事件出错啦---",error);
            }
        });
        // --- 子页面window缩放时
        $(window).off("resize").on("resize",_.debounce(function(){
            //alert("snoanfoawfn");
        },200));
    }
    // --- 处理iframe无法触发点击事件(未使用)
    window.zzIframeOnClick_202012251111 = {  
        resolution: 200,  
        iframes: [],  
        interval: null,  
        Iframe: function() {  
            this.element = arguments[0];  
            this.cb = arguments[1];   
            this.hasTracked = false;  
        },  
        track: function(element, cb) {  
            this.iframes.push(new this.Iframe(element, cb));  
            if (!this.interval) {  
                var _this = this;  
                this.interval = setInterval(function() { _this.checkClick(); }, this.resolution);  
            }  
        },  
        checkClick: function() {  
            if (document.activeElement) {  
                var activeElement = document.activeElement;  
                for (var i in this.iframes) {  
                    if (activeElement === this.iframes[i].element) { // user is in this Iframe  
                        if (this.iframes[i].hasTracked == false) {   
                            this.iframes[i].cb.apply(window, []);   
                            this.iframes[i].hasTracked = true;  
                        }  
                    } else {  
                        this.iframes[i].hasTracked = false;  
                    }  
                }  
            }  
        }  
    };
    /* 子页面相关 ---E */
    //-------------------------------------------------------------

})();